package com.zll.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @BelongsProject: springcloudnetflix-parent
 * @BelongsPackage: cn.itsource.filter
 * @Author: Director
 * @CreateTime: 2022-07-29  17:59
 * @Description: 自定义一个计算请求调用链耗时的filter
 * @Version: 1.0
 */
public class RequestTimeFilter implements GatewayFilter, Ordered {

    // 创建日志器，可以使用slf4j提供的日志器进行日志打印
    private static final Logger log = LoggerFactory.getLogger(RequestTimeFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 打印当前客户端请求的地址
        String path = exchange.getRequest().getURI().getPath();
        log.info("用户ip地址为：{}", path);

        // 存入进入请求时的开始时间
        exchange.getAttributes().put("startTime", System.currentTimeMillis());

        // 执行完成之后
        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    // 开始时间
                    Long startTime = exchange.getAttribute("startTime");
                    // 结束时间
                    Long endTime = (System.currentTimeMillis() - startTime);
                    // 打印当前请求耗时
                    log.info(exchange.getRequest().getURI().getRawPath() + ": " + endTime + "ms");
                })
        );
    }

    /*
     * @Description: 执行时机，默认为0
     * @Author: Director
     * @Date: 2022/7/29 18:07
     * @return: int
     **/
    @Override
    public int getOrder() {
        return 0;
    }
}